import subprocess

from django.core.management.base import NoArgsCommand
from django.conf import settings

class Command(NoArgsCommand):
    def handle_noargs(self, **options):
        httpd_text = """Alias /js/ {path}/static/js/
Alias /css/ {path}/static/css/
Alias /img/ {path}/static/img/

<Directory {path}/static/>
Order deny,allow
Allow from all
</Directory>

WSGIScriptAlias / {path}/wsgi.py

<Directory {path}/>
Order deny,allow
Allow from all
</Directory>
"""

        cron_text = """SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow command
*/30 *   * * *   cd {path}/stream && python updater.py > /dev/null
"""
        try:
            httpd_text = httpd_text.replace('{path}', settings.PROJECT_ROOT)
            httpd_file = open('/etc/apache2/httpd.conf', 'w')
            httpd_file.write(httpd_text)
            httpd_file.close()
        except Exception, e:
            print e

        try:
            cron_text = cron_text.replace('{path}', settings.PROJECT_ROOT)
            cron_proc = subprocess.Popen('crontab', shell = True, stdin=subprocess.PIPE, stdout = subprocess.PIPE)
            response = cron_proc.communicate(cron_text)
            def printResponseItem(item, header):
                if item is not None and item != '':
                    print item

            printResponseItem(response[0], 'stdout')
            printResponseItem(response[1], 'stdout')
        except Exception, e:
            print e
